#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.api_security import APISecurity
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from utility import tools
from utility import his_api
from command.handler import dict_handler
import logging

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class ArchivesBindAPI(Resource):
    """
    绑定孕妇
    :request: post
    ：param archivesId: 档案Ids
    :returns: json string
    """
    def post(self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})  
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            # 更新孕妇archivesId
            query_ = [('id', '=',int(payload['aud']))]
            user = odoo.env['res.users'].search(query_)
            if not user:
                return jsonify({'code': 900, 'msg': error_code[900]}) 
            data_={'archives_id': int(params.get('archivesId'))}    
            odoo.env['res.users'].write(user,data_)
            # 记录操作日志
            create_event = event_type.OperationLogEvent('绑定孕妇', '用户id：{}'.format(payload['aud']))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DictionariesGetAllAPI(Resource):
    """
    获取全部字典
    :request: get
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            odoo = OdooManager().get_instance()    
            fields_ = ['name','key','value','description','sequence']    
            dict_dictionary = odoo.env['dict.dictionary'].search_read(fields = fields_)
            data_ = {}
            if dict_dictionary:
                for  dict_ in dict_dictionary:
                    if dict_['name'] not in data_.keys():
                        data_[dict_['name']] = []
                    dict_tmp = {
                        'dictTitle': dict_['value'],
                        'dictSort': dict_['sequence'],
                        'dictValue': dict_['key'],
                        'dictId': dict_['id']
                    }    
                    data_[dict_['name']].append(dict_tmp)    
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DictionariesGetByTypeAPI(Resource):
    """
    获取字典-通过类型获取单个字典
    :request: get
    :param dictTypeCode: 字典类型
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            req_params = ['dictTypeCode']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            odoo = OdooManager().get_instance()    
            query_ = [('name', '=', params.get('dictTypeCode'))]
            fields_ = ['name','key','value','description','sequence']    
            dict_dictionary = odoo.env['dict.dictionary'].search_read(query_,fields = fields_)
            data_ = {}
            if dict_dictionary:
                for  dict_ in dict_dictionary:
                    if dict_['name'] not in data_.keys():
                        data_[dict_['name']] = []
                    dict_tmp = {
                        'dictTitle': dict_['value'],
                        'dictSort': dict_['sequence'],
                        'dictValue': dict_['key']
                    }    
                    data_[dict_['name']].append(dict_tmp)    
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class CommonQueryDoctorAPI(Resource):
    """
    模糊查询医生
    :request: get
    :param keyword: 关键字
    :param postId: 职位ID
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            odoo = OdooManager().get_instance()   
            query_ = []
            if params.get('keyword'): 
                query_.append(('name', 'like', str(params.get('keyword'))))
            fields_ = ['name','id']
            res_doctor = odoo.env['hr.employee'].search_read(query_,fields = fields_)
            data_ = {'rows': [],'total': 0}
            if res_doctor:
                for  doctor_ in res_doctor:
                    data_tmp = {
                        'ysXm': doctor_['name'],
                        'ysCode': '',
                        'ysId': doctor_['id']
                    }    
                    data_['rows'].append(data_tmp)   
                    data_['total'] +=1
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class CommonQueryHospitalAPI(Resource):
    """
    模糊查询医院
    :request: get
    :param keyword: 关键字
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            odoo = OdooManager().get_instance()   
            query_ = []
            if params.get('keyword'): 
                query_.append(('name', 'like', str(params.get('keyword'))))
            fields_ = ['name','code','id']    
            res_hospital = odoo.env['res.hospital'].search_read(query_,fields = fields_)
            data_ = {'rows': [],'total': 0}
            if res_hospital:
                for  hospital_ in res_hospital:
                    data_tmp = {
                        'yyXm': hospital_['name'],
                        'yyCode': hospital_['code'],
                        'yyId': hospital_['id']
                    }    
                    data_['rows'].append(data_tmp)   
                    data_['total'] +=1
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class RegionTreeGetAPI(Resource):
    """
    获取省市区数据
    :request: get
    :param parentCode: 父ID  传0是第一级
    :param level: level
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            req_params = ['parentId', 'level']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            odoo = OdooManager().get_instance()
            query_ = [
                ('parent_id','=',False if int(params.get('parentId')) == 0 else int(params.get('parentId'))),
                ('level', '=',int(params.get('level')))
            ]
            fields_ = ['name','level','parent_id', 'id']
            res_region = odoo.env['res.region'].search_read(query_,fields = fields_)
            data_ = []
            if res_region:
                for  region_ in res_region:
                    region_tmp = {
                        'id': region_['id'],
                        'label': region_['name'],
                        'level': region_['level'],
                        'parentId': region_['parent_id'],
                        'isLast':0
                    }
                    children_data = odoo.env['res.region'].search_read([('parent_id', '=', region_tmp['id'])], ['id'])
                    if (children_data == None or len(children_data) == 0):
                        region_tmp['isLast'] = 1
                    data_.append(region_tmp)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetBindAPI(Resource):
    """
    获取绑定孕妇
    :request: get
    :returns: json string
    """
    def get(self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 获取archivesId
            query_ = [('id', '=',int(payload['aud']))]
            user = odoo.env['res.users'].search_read(query_)
            if not user:
                return jsonify({'code': 900, 'msg': error_code[900]})
            archivesId=user[0]['archives_id']
            if not archivesId:
                return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': 'true'})
            archivesId=archivesId[0]
            archives_ = odoo.env['res.archives'].search_read([('id', '=', int(archivesId))])
            if not archives_:
                return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': 'true'})
            #  返回前端数据结构初始化
            archives_ = archives_[0]
            # 获取初检档案
            cjda_info = odoo.env['inspection.initial'].search_read([('archives_id', '=', archives_['id'])])
            if cjda_info:
                cjda_info = cjda_info.pop()
            archives_vo = {
                'archivesId': archives_['id'],  # 档案Id
                # 'archivesId': archives_['jbzlid'], # 档案Id
                'mqAge': archives_['mq_age'], # 母亲年龄
                'mqMz': archives_['mq_mz'], # 民族
                'mqSfz': archives_['mq_sfz'], # 身份证
                'mzNum': archives_['mzh'], # 门诊号
                'mcyjsj': archives_['mcyjsj'], # 末次月经时间
                'imgUrl': archives_['img_url'], # 头像
                'mqXm': archives_['mq_xm'], # 姓名
                'cc': cjda_info['ycs_cc'] if cjda_info else 0, # 产次默认0检验初检表产次是否存在,存在进行替换
                'yc': cjda_info['ycs_yc'] if cjda_info else 0, # 孕次默认0检验初检表孕次是否存在,存在进行替换
                'yz': tools.parase_yz(1, archives_['yz']), # 孕周
                'step': {'yfjd': 1,'yqcj': 0,'cgcj': 0,'cqsc': 0,'ch42': 0,'fmjl': 0}, # 步骤:孕妇建档,孕期初检,常规产检,产前筛查,产后42天,分娩记录
                'gwys' : archives_['gwys_ids'], # 高危因素列表
                'gwColor' : dict_handler.get_dict_value(archives_['danger_color'],'ck_gwys'), # 高危颜色
                'gwColorCode' : archives_['danger_color'], # 高危颜色编码
                'hljb' : archives_['hl_dj'], # 护理级别(有则返回)
                'ks' : archives_['mq_sfz'], # 科室(有则返回)
                'zyh' : archives_['zyh'], # 住院号(有则返回)
                'ch' : archives_['bed'], # 床号(有则返回 )
            }
            # 更新高危因素
            if archives_['gwys_ids']:
                gwys_list = odoo.env['dict.gwys'].search_read([('id', 'in', archives_['gwys_ids'])], ['name', 'code', 'id'])
                archives_vo['gwys'] = gwys_list
            #  更新产次,孕次
            initial_ = odoo.env['inspection.initial'].search_read([('archives_id', '=', int(archivesId))])
            if initial_:
                initial_=initial_[0]
                if initial_['ycs_yc']:
                    archives_vo['cc'] = initial_['ycs_cc'] 
                if initial_['ycs_yc']:
                    archives_vo['yc'] = initial_['ycs_yc'] 
            #  更新步骤  
            inspection_log_ = odoo.env['inspection.log'].search_read([('archives_id', '=', int(archivesId)), ('state', 'in', ['0', '1'])])
            if inspection_log_:
                for log_ in inspection_log_:
                    if log_['type'] == '1':
                        archives_vo['step']['yqcj'] = 1
                    elif  log_['type'] == '2':
                        archives_vo['step']['cgcj'] = 1  
                    elif  log_['type'] == '3':
                        archives_vo['step']['ch42'] = 1    
            birth_record_ = odoo.env['birth.record'].search_read([('archives_id', '=', int(archivesId))])
            if birth_record_:
                archives_vo['step']['fmjl'] = 1   
            inspection_tang_case_ = odoo.env['inspection.tang.case'].search_read([('archives_id', '=', int(archivesId))])
            if inspection_tang_case_:
                archives_vo['step']['cqsc'] = 1             
            return jsonify({'code': 0, 'msg': 'success', 'data': archives_vo, 'success': 'true'})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesDeBindAPI(Resource):
    """
    解绑孕妇
    :request: get
    :param dictTypeCode: 字典类型
    :returns: json string
    """
    def get(self):
        try:
            # token校验
            
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})
            
              
            odoo = OdooManager().get_instance()
            # 解绑孕妇archivesId
            query_ = [('id', '=',int(payload['aud']))]
            user = odoo.env['res.users'].search(query_)
            if not user:
                return jsonify({'code': 900, 'msg': error_code[900]}) 
            data_={'archives_id': ''}    
            odoo.env['res.users'].write(user,data_)
            # 记录操作日志
            create_event = event_type.OperationLogEvent('解绑孕妇', '用户id：{}'.format(payload['aud']))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class RegistrationListAPI(Resource):
    """
    获取挂号列表
    :request: get
    :param registerDate: 日期 非必填
    :param cureDept: 门诊号 非必填
    :returns: json string
    """
    def get(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.values
            data_ = {
                "await": [],
                "nowing": [],
                "finished": []
            }
            his_ = his_api.APIHis()
            records_list = his_.get_pacs_web_report(registerDate=params.get('registerDate'),cureDept=params.get('cureDept'))
            if records_list:
                for record_ in records_list:
                    record_tmp = {
                        'name': record_['name'],
                        'idCard': record_['cardNo'],
                        'date': record_['registerDate'],
                        'status': 0,
                        'type': 0,
                        'gwColorCode': '',
                        'archivesId': '',
                        'address': record_['address'],
                        'nation': record_['nation']
                    }
                    #  更新档案信息
                    query_ = [('mq_sfz', '=', params.get('cardNo'))]
                    res_archive = odoo.env['res.archives'].search_read(query_,['id','max_gwys'])
                    if res_archive:
                        res_archive = res_archive[0]
                        record_tmp['status'] = 1
                        record_tmp['gwColorCode'] = res_archive['max_gwys']
                        record_tmp['archivesId'] = res_archive['id']
                    #  1000:候诊 1001:在诊 9999:已诊
                    if record_['state'] == '1000':
                        data_['await'].append(record_tmp)
                    elif record_['state'] == '1001':
                        record_tmp['type'] = 1
                        data_['nowing'].append(record_tmp)  
                    else:
                        record_tmp['type'] = 2
                        data_['finished'].append(record_tmp)  
            return jsonify({'code': 0, 'msg': 'success', 'data':data_ })
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class CheckingDetailAPI(Resource):
    """
    查询在途检查情况
    :request: get
    :returns: json string
    """
    def get(self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})
               
            #  获取archivesId
            odoo = OdooManager().get_instance()
            query_ = [('id', '=',int(payload['aud']))]
            user = odoo.env['res.users'].search_read(query_)
            data_ = {
                'type': None,
                'checkProgressVo': []
            }
            if not user:
                return jsonify({'code': 900, 'msg': error_code[900]})
            archivesId=user[0]['archives_id']
            if not archivesId:
                return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': 'true'})
            #  查询在途检查情况
            archivesId=archivesId[0]
            query_ = [('archives_id', '=', archivesId),('state', '=', '0')]
            inspection_logs = odoo.env['inspection.log'].search_read(query_)
            if not inspection_logs:
                return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': 'true'})
            inspection_logs = inspection_logs.pop()
            data_={
                    'type': inspection_logs['type'],
                    'checkProgressVo': []    
                }
            # 如果是初检 则更新初检档案
            # 更新问询
            if inspection_logs['type'] == '1':
                cjda = {'type': 4,'finish': False, 'doctor': '','date': ''}
                if inspection_logs['cjda_id']:
                    query_ = [('inspection_log_id', '=', int(inspection_logs['id'])), ('id', '=', inspection_logs['cjda_id'][0])]
                    inspection_initial = odoo.env['inspection.initial'].search_read(query_)
                    if inspection_initial:
                        inspection_initial = inspection_initial[0]
                        cjda['finish'] = True
                        cjda['doctor'] = inspection_initial['create_uid'][1] if inspection_initial['create_uid'] else None
                        cjda['date'] = inspection_initial['create_date']
                data_['checkProgressVo'].append(cjda)
            else:
                wx_iz={'type': 0,'finish': False, 'doctor': '','date': ''}
                if inspection_logs['wx_id']:
                    query_ = [('inspection_log_id', '=', inspection_logs['id']), ('id', '=', inspection_logs['wx_id'][0])]
                    inspection_inquires = odoo.env['inspection.inquiries'].search_read(query_)
                    if inspection_inquires:
                        inspection_inquires = inspection_inquires[0]
                        wx_iz['finish'] = True
                        wx_iz['doctor'] = inspection_inquires['create_uid'][1] if inspection_inquires['create_uid'] else None
                        wx_iz['date'] = inspection_inquires['create_date']
                data_['checkProgressVo'].append(wx_iz)
            # 更新体格检查
            tgjx={'type': 1,'finish': False,'doctor': '','date': ''}
            if inspection_logs['tgjx_id']:
                query_ = [('inspection_log_id', '=', inspection_logs['id']), ('id', '=', inspection_logs['tgjx_id'][0])]
                inspection_physical = odoo.env['inspection.physical'].search_read(query_)
                if inspection_physical:
                    tgjx['finish'] = True
                    tgjx['doctor'] = inspection_physical[0]['create_uid'][1] if inspection_physical[0]['create_uid'] else None
                    # tgjx['doctor'] = inspection_physical.cg_tjrq  数据表无此字段 只有hospital_id
                    tgjx['date'] = inspection_physical[0]['cg_tjrq']
            data_['checkProgressVo'].append(tgjx)                 
            # 更新实验室辅助检查
            sysfzjc={'type': 2,'finish': False,'doctor': '','date': ''}
            if inspection_logs['sys_id']:
                query_ = [('inspection_log_id', '=', inspection_logs['id']), ('id', '=', inspection_logs['sys_id'][0])]
                inspection_laboratory = odoo.env['inspection.laboratory'].search_read(query_)
                if inspection_laboratory:
                    inspection_laboratory = inspection_laboratory.pop()
                    sysfzjc['finish'] = True
                    sysfzjc['doctor'] = inspection_laboratory['create_uid'][1] if inspection_laboratory['create_uid'] else None # 数据表无此字段 只有hospital_id
                    sysfzjc['date'] = inspection_laboratory['create_date'] #数据表无此字段
            data_['checkProgressVo'].append(sysfzjc)       
            # 更新诊断处理
            zdcl={'type': 3,'finish': False,'doctor': '','date': ''}
            if inspection_logs['zdcl_id']:
                query_ = [('inspection_log_id', '=', inspection_logs['id']), ('id', '=', inspection_logs['zdcl_id'][0])]
                inspection_diagnostic = odoo.env['inspection.diagnostic'].search_read(query_)
                if inspection_diagnostic:
                    inspection_diagnostic = inspection_diagnostic.pop()
                    zdcl['finish'] = True
                    zdcl['doctor'] = inspection_diagnostic['cl_ys_id'][1] if inspection_diagnostic['cl_ys_id'] else None
                    zdcl['date'] = inspection_diagnostic['cl_zdsj']
            data_['checkProgressVo'].append(zdcl)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class CheckingAbandonAPI(Resource):
    """
    放弃在途检查
    :request: get
    :returns: json string
    """
    def get(self):
        try:
            
            #  token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})
            
            #payload = {'aud': 2}       
            #  获取archivesId
            odoo = OdooManager().get_instance()
            query_ = [('id', '=',int(payload['aud']))]
            user = odoo.env['res.users'].search_read(query_)
            if not user:
                return jsonify({'code': 900, 'msg': error_code[900]})
            archivesId=user[0]['archives_id']
            if not archivesId:
                return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': 'true'})
            #  查询在途检查情况
            archivesId=archivesId[0]
            query_ = [('archives_id', '=', archivesId),('state', '=', '0')]
            inspection_logs = odoo.env['inspection.log'].search(query_)[0]
            if not inspection_logs:
                return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': 'true'})
            data_={ 'state': '2' }
            odoo.env['inspection.log'].write(inspection_logs,data_)
            # 记录操作日志
            create_event = event_type.OperationLogEvent('放弃在途检查', '用户id：{},档案id{}'.format(payload['aud'],archivesId))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})